<template>
  <div class="order-upload-img-component">
    <!-- 价格明细上传 -->
    <el-upload v-if="imgType === 'price'" class="upload_price_pictures" :ref="imgType" action="" :on-preview="handlePreview" :on-remove="handleRemove" :on-change="handleChange" :auto-upload="false" list-type="picture">
      <el-button slot="trigger" type="text" v-show="fileList.length === 0">{{order.price_pictures ? '编辑' : '选择文件'}}</el-button>
      <el-button style="margin-left: 10px;" v-show="fileList.length > 0" type="text" @click="submitUpload(imgType)" :loading="loading">{{ loading ? '上传中' : '上传' }}</el-button>
    </el-upload>

    <!-- 测量或者安装图纸上传 -->
    <el-upload v-if="['measure_pictures', 'completed_pictures'].indexOf(imgType) !== -1" :ref="imgType" class="upload_measure_pictures" action="" list-type="picture-card" :on-change="handleChange" :auto-upload="false">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-button v-if="['measure_pictures', 'completed_pictures'].indexOf(imgType) !== -1" type="success" :loading="loading" v-show="fileList.length > 0" @click="submitUpload(imgType)">{{ loading ? '上传中' : '上传' }}</el-button>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  props: {
    imgType: {
      required: true,
      type: String
    }
  },
  data: () => ({
    fileList: [],
    pictures: [],
    loading: false,
  }),
  computed: {
    ...mapGetters('orders', [
      'order'
    ])
  },
  methods: {
    ...mapActions('orders', [
      'uploadImg'
    ]),
    handleRemove(file, fileList) {
      // console.log(file, fileList)
    },
    handlePreview(file) {
      // console.log(file)
    },
    handleChange(file, fileList) {
      this.fileList = fileList
      // console.log(fileList)
    },
    submitUpload(uploadName) {
      let data = new FormData()
      this.pictures.map(item => {
        data.append('pictures[][image]', item.image);
        data.append('pictures[][image_type]', item.iamge_type);
      })
      this.loading = true
      this.uploadImg({ id: this.order.id, data: data }).then((res) => {
        if (res) {
          this.$message({
            message: '图片上传成功，请查看！',
            type: 'success'
          });
        } else {
          this.$message({
            message: '图片上传失败，请重试！',
            type: 'error'
          });
        }
        this.loading = false
      }).then(() => {
        this.$refs[uploadName].clearFiles()
        this.fileList = []
        this.pictures = []
      })

    },
  },
  watch: {
    fileList(val, oldVal) {
      this.pictures = val.map(item => {
        return { image: item.raw, iamge_type: this.imgType }
      })
    }
  }
}
</script>

<style lang="scss">
.order-upload-img-component {
  .upload_price_pictures {
    margin-left: 10px;
  }

  .upload_measure_pictures {
    .el-upload {
      margin: 0 8px 8px 0 !important;
    }
  }
}
</style>
